package com.snake.excel2java.excel;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import com.snake.excel2java.excel.global.GlobalData;
import com.snake.excel2java.excel.global.GlobalDataExt;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import net.sf.json.JSONObject;

@Slf4j
public class GlobalLoader implements IExcelLoader {

	public static final int START_LINE = 2;
	
	// 加载时间
	protected long loadTime;
	
	protected GlobalDataExt globalDataExt;

	@Override
	public String getJavaName() {
		// TODO Auto-generated method stub
		return "Global";
	}

	@Override
	public String getFileName() {
		// TODO Auto-generated method stub
		return "global.xlsx";
	}

	@Override
	public String getDesc() {
		// TODO Auto-generated method stub
		return "";
	}
	
	@Override
	public String[] getPropNames() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean load(String path) {
		
		log.info("\r\n\r\n\r\n------------- read {} --------------", path + getFileName());
		
		boolean result = true;
		int i = START_LINE;
		XSSFWorkbook workbook2007 = null;
		try {
			
			workbook2007 = new XSSFWorkbook(path + getFileName());
			XSSFSheet sheet = workbook2007.getSheetAt(0);
			
//			FormulaEvaluator evaluator = sheet.getWorkbook()
//											  .getCreationHelper()
//											  .createFormulaEvaluator();  
//			evaluator.evaluateAll();
			
			int length = sheet.getLastRowNum() + 1;
			
			StringBuilder builder = new StringBuilder();
			
			Set<String> nameSet = new HashSet<String>();
			for(String str: GlobalData.NAMES)
				nameSet.add(str);
			
			builder.append("{");
			
			int gParaSize = 0;
			for( ; i < length; ++i) {
				
				XSSFRow row = sheet.getRow(i);//类型
				
				if(null == row)
					continue;
				
				String para = readString(row, 0);
				
				if(null == para)
					continue;
				
				if(!nameSet.contains(para))
					continue;
				
				String type = readString(row, 2);
				String value = readConvertString(row, 4, type);
				
				if(i > START_LINE)
					builder.append(", ");
				
				builder.append("\"")
					   .append(para)
					   .append("\":")
					   .append(value);
				
				gParaSize++;
				
			}
			
			builder.append("}");
			
			log.info("global json: {}", builder.toString());
			
			if(nameSet.size() != gParaSize) {
				
				log.error("加载全局表失败, 缺少数据, 应该加载: {}, 实际加载: {}", nameSet.size(), gParaSize);
				
				throw new Exception("加载全局表失败, 缺少数据");
			}
			
			JSONObject jsonObject= JSONObject.fromObject(builder.toString());
			
			GlobalDataExt loadedGlobal = (GlobalDataExt) JSONObject.toBean(jsonObject,GlobalDataExt.class);
			
			loadedGlobal.parse();
			
			log.info("load global: {}", jsonObject);
			
			globalDataExt = loadedGlobal;
			loadTime = System.currentTimeMillis();
						
			log.info("file {} loaded\r\n\r\n", getFileName());
			
		} catch (Exception e) {
			
			log.error("read file {} error in line {}........", getFileName(), i);
						
			e.printStackTrace();
			
			result = false;
									
		} finally {
			
			try {
				workbook2007.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				log.error("close file {} error: {}", getFileName(), e.getMessage());
			}
		}
		
		return result;
	}
	
	// 加载完成后，做其他操作
	protected void parse() {
		
	}
	
	protected String readConvertString(XSSFRow row, int index, String type) {
		
		switch (type) {
		case "bool":
		case "int":
		case "float":
			return readString(row, index);
			
		case "string":
			
			return "\"" + readString(row, index) + "\"";
			
		case "string[]":
			
			String value =  readString(row, index);
			
			String[] strArr =  value.split(",");
			
			String result = "";
			
			for(String temp: strArr) {
				
				if(!result.isEmpty())
					result += ",";
				
				result+= "\"" + temp + "\"";
			}
				
			return "[" + result + "]";
			
		default:
			return "[" + readString(row, index) + "]";
		}
		
	}
	
	// 读取 String, 移除前后空格
	// 数组类型为String
	// 数组类型只包含一个，转换为String
	// 其他未识别的类型为String
	protected String readString(XSSFRow row, int index) {

		XSSFCell cell = row.getCell(index);	
		
		if(null == cell)
			return null;
		
		return cell.getStringCellValue().trim();

	}
	


}
